package com.lebang.service.cences;

import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesClick;
import com.lebang.domain.MemberClidkRouseRecord;
import com.lebang.example.CencesClickExample;
import com.lebang.mapper.CencesClickMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.MemberClidkRouseRecordMapper;
import com.lebang.mapper.TaskRouseMapper;
import com.lebang.model.MyConfig;
import com.lebang.model.cences.CencesMsg;
import com.lebang.model.enums.buss.RewardTypeUscan;
import com.lebang.service.BaseService;
import com.lebang.service.mongodb.CencesMsgMongodb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计
 *
 * @Author hwq
 * @Date 2020-02-09
 */
@Service
@Slf4j
public class CencesClickService extends BaseService<CencesClick, Integer, CencesClickExample> {
    @Autowired
    private CencesClickMapper baseMapper;
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private TaskRouseMapper taskRouseMapper;
    @Autowired
    private MemberClidkRouseRecordMapper memberClidkRouseRecordMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;

    public void starDataInit(LocalDateTime end) {
        this.starDataInit(end,null);
    }
    public void starDataInit(LocalDateTime end, List<String> brand) {
        long starTime=System.currentTimeMillis();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime star = end.minusDays(1);
        LocalDate starDate = star.toLocalDate();
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        List<CencesClick> cencesMasters = new ArrayList<>();
        if(brand==null){
            brand=lbbMemberMapper.selectBrand();
        }
        List<Integer> sdkKey = taskRouseMapper.selectAllId();

        List<MemberClidkRouseRecord> memberClidkRouseRecords = memberClidkRouseRecordMapper.selectByDate(star, end);
        memberClidkRouseRecords.forEach(s->{s.setAppStoreRouseId(s.getAppStore()+":"+s.getRouseId());});
        Map<String,List<MemberClidkRouseRecord>> clickRecordMap = memberClidkRouseRecords.stream().collect(Collectors.groupingBy(MemberClidkRouseRecord::getAppStoreRouseId));

        //全部用户的
        List<String> finalBrand = brand;
        sdkKey.forEach(key -> {
            finalBrand.forEach(s -> {
                CencesClick newVo = new CencesClick(0, s, time, 1, key, 0, MyConfig.getEnv());
                CencesClick oldVo = new CencesClick(0, s, time, 0, key, 0, MyConfig.getEnv());
                CencesClick allVo = new CencesClick(0, s, time, 2, key, 1, MyConfig.getEnv());

                countClick(newVo,oldVo,allVo,s,key,clickRecordMap,starDate);
                cencesMasters.add(newVo);
                cencesMasters.add(oldVo);
                baseMapper.insertClick(allVo);
                baseMapper.insertClick(newVo);
                baseMapper.insertClick(oldVo);
            });
        });

        //总数计算
        CencesClick item = new CencesClick(0, "all", time, 2, 0, 1, MyConfig.getEnv());
        //新用户全部
        CencesClick newAll = new CencesClick(0, "all", time, 1, 0, 1,MyConfig.getEnv());
        //老用户全部
        CencesClick oldAll = new CencesClick(0, "all", time, 0, 0, 1,MyConfig.getEnv());
        cencesMasters.forEach(vo -> {
            sumBy(item, vo);
            if (vo.getCategory().equals(1)) {
                sumBy(newAll, vo);
            }
            if (vo.getCategory().equals(0)) {
                sumBy(oldAll, vo);
            }

        });
        baseMapper.insertClick(item);
        baseMapper.insertClick(newAll);
        baseMapper.insertClick(oldAll);
        //数据源的全部

        sdkKey.forEach(key -> {
            CencesClick sjy = new CencesClick(0, "all", time, 2, key, 1,MyConfig.getEnv());
            //新用户全部
            CencesClick newAlldata = new CencesClick(0, "all", time, 1, key, 1,MyConfig.getEnv());
            //老用户全部
            CencesClick oldAlldata = new CencesClick(0, "all", time, 0, key, 1,MyConfig.getEnv());
            cencesMasters.forEach(vo -> {
                if (vo.getSdkKey().equals(key)) {
                    sumBy(sjy, vo);
                    if (vo.getCategory().equals(1)) {
                        sumBy(newAlldata, vo);
                    } else {
                        sumBy(oldAlldata, vo);
                    }
                }
            });
            baseMapper.insertClick(sjy);
            baseMapper.insertClick(oldAlldata);
            baseMapper.insertClick(newAlldata);
        });
        //渠道的全部
        brand.forEach(s -> {
            CencesClick sjy = new CencesClick(0, s, time, 2, 0, 1,MyConfig.getEnv());
            //新用户全部
            CencesClick newAlldata = new CencesClick(0, s, time, 1, 0, 1,MyConfig.getEnv());
            //老用户全部
            CencesClick oldAlldata = new CencesClick(0, s, time, 0, 0, 1,MyConfig.getEnv());
            cencesMasters.forEach(vo -> {
                if (vo.getBrand().equals(s)) {
                    sumBy(sjy, vo);
                    if (vo.getCategory().equals(1)) {
                        sumBy(newAlldata, vo);
                    } else {
                        sumBy(oldAlldata, vo);
                    }
                }

            });
            baseMapper.insertClick(sjy);
            baseMapper.insertClick(oldAlldata);
            baseMapper.insertClick(newAlldata);
        });
        cencesMsgMongodb.save(new CencesMsg("每日必赚签到统计",(System.currentTimeMillis()-starTime)));
    }




    public CencesClick sumData(Integer star, Integer end, String appStore, int category, int type, Integer sdkKey,String likeBrand,Integer appId) {
        return baseMapper.sumData(star, end, appStore, category, type, sdkKey,likeBrand,appId);
    }

    private void sumBy(CencesClick item, CencesClick vo) {
        item.setClickCount(item.getClickCount() + vo.getClickCount());
        item.setClickRebate(item.getClickRebate().add(vo.getClickRebate()));
    }

    private void record(MemberClidkRouseRecord v, CencesClick newVo) {
        //签到数

        newVo.setClickCount(newVo.getClickCount() + 1);


        if (v.getRewardType() .equals(RewardTypeUscan.Point.getIndex())) {
            newVo.setClickRebate(newVo.getClickRebate().add(new BigDecimal(v.getWorth()).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_DOWN)));
        } else {
            newVo.setClickRebate(newVo.getClickRebate().add(new BigDecimal(v.getWorth()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
        }

    }

    public int deleteByTime(int time) {
        CencesClickExample earnDayExample = new CencesClickExample();
        earnDayExample.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        return baseMapper.deleteByExample(earnDayExample);
    }

    /**
     * 统计签到数
     * @param newVo 新用户
     * @param oldVo 老用户
     * @param allVo 全部用户
     * @param appStore 渠道
     * @param rouseId 签到id
     * @param clickRecordMap 点击记录
     */
    private void countClick(CencesClick newVo, CencesClick oldVo, CencesClick allVo, String appStore, Integer rouseId, Map<String, List<MemberClidkRouseRecord>> clickRecordMap,LocalDate starDate) {
        List<MemberClidkRouseRecord> list= clickRecordMap.get(appStore+":"+rouseId);
        if(null == list){
            return;
        }
        list.forEach(v -> {
            if (v.getCreateTime().toLocalDate().equals(starDate)) {
                //今天新增的用户
                this.record(v, newVo);
            } else {
                //老用户
                this.record(v, oldVo);
            }
            this.record(v, allVo);
        });

    }

    @DataSource("commonDB")
    public long countClick(CencesClickExample example) {
        return baseMapper.countByExample(example);
    }

    @DataSource("commonDB")
    public List<CencesClick> selectClick(CencesClickExample example) {
        return baseMapper.selectByExample(example);
    }
}
